export const useTableInit = ({ state, tableData, columns, resultList, searchFun })  =>{
  // 初始化state
  function initState(keyOptions) {
    // 所有的数据都从这里走的，点击时获取到对应的参数。放入state里
    columns.forEach((el) => {
      state.value[el.key] = {}
    })

    // 获取colums种的options放入state里
    columns.forEach((el) => {
      try{
        state.value[el.key].formType = el.formType
        const item = state.value[el.key]
        if(el.editx) item.show = true
        if (el.formType === 'select' || el.formType === 'cascader') {
          try{
            item.options = el.options?.length ? el.options : setOptions(keyOptions,el.key)
            item.memory =  JSON.parse(JSON.stringify(item.options))
            item.placeholder = el.placeholder  ? item.placeholder : ''
          }catch{
            console.log('动态值为空')
          }
        } else if (el.formType === 'input' || el.formType === 'time') {
          item.inputValue = ''
          item.placeholder = el.placeholder ? el.placeholder : ''
        } else if(!el.formType){
          delete state.value[el.key]
        }
      }catch{
        // console.log(el)
      }
    })
    // console.log(state.value,'state',columns);
    
  }

  // 设置options
  function setOptions(data,key){
    return data.value[key] || []
  }

  // 通过Columns 获取state的options
  function getColumns(column, searchText) {
    let options = state.value[column.key].memory
    //获取筛选的数据选项
    if(searchText){
      const list = []
      if(options.length){
        options.forEach(v =>{
          if(v.label.includes(searchText)){
            list.push(v)
          }
        })
      }
      return list
    }else{
      return options
    }
  }

  // 获取筛选
  function getResult(column){
    // console.log(column,'column')
    try{
      const current = state.value[column.key];
      const checkedList = current.checkedList;
      if(column.formType === 'select' || column.formType === 'cascader'){
        state.value[column.key].requestValueList = checkedList
      } else{
        state.value[column.key].requestValue = current.inputValue
      }
      const options = current.memory || current.options
      let result = []
      if (checkedList?.length > 0) {
        if(column.formType === 'cascader'){
          // cascader 返回格式不统一，暂不支持
          let ids = []
          checkedList.forEach(v =>{
            if(v.length) ids.push(v[2])
          })
          result = findNamesByIds(options, ids)
        }else{
          options.forEach((el) => {
            checkedList.forEach((item) => {
              if (el.value === item) {
                result.push(el.label);
              }
            });
          });
        }
      }
      let isExistedRow = resultList.value.find((el) => el.key == column.key);
      // if (checkedList?.length === 0 && isExistedRow) {
      //   resultList.value = resultList.value.filter((el) => el.key != column.key);
      //   return;
      // }
      let resStr = ''
      if(column.formType === 'select' || column.formType === 'cascader'){
        if(result.length > 3){
          resStr = result.slice(0, 3).join('、') + ' 等'
        }else{
          resStr = result.join('、')
        }
      }else if(column.formType === 'time' && Array.isArray(current.inputValue) && current.inputValue.length == 2){
        resStr = current.inputValue.join(' - ')
      }else{
        resStr = current.inputValue
      }
      const finalMap = {
        label: column.title,
        key: column.key,
        value: `${column.title}：${resStr}`,
        inputValue: current.inputValue,
        checkedList: current.checkedList,
        formType: column.formType,
        params: column.params,
      };
      // console.log(isExistedRow,'isExistedRow');
      // console.log(resultList.value,'resultList.value',column.key);
      if (isExistedRow) {
        let index = resultList.value.findIndex((el) => el.key == column.key)
        resultList.value.splice(index, 1, finalMap)
        // console.log(resultList.value,'xxxxx');
        // isExistedRow.value = finalMap.value;
      } else if(!isExistedRow && resStr) {
        resultList.value.push(finalMap);
      }
    }catch(err){
      console.log(err)
    }
  }

  // 递归获取name集合
  function findNamesByIds(data, ids, result = []) {
    data.forEach(item => {
      if (ids.includes(item.value)) {
        // 匹配到对应的 id，推送 name 到结果数组中
        result.push(item.startTimeEndTime)
      }
      // 如果有子节点，继续递归遍历
      if (item.children && item.children.length > 0) {
        findNamesByIds(item.children, ids, result)
      }
    })
    return result
  }

  // 全选的时候获取参数
  function onCheckAllChange(column){
    let v = state.value[column.key]
    v.indeterminate = false
    if (v.checkAll) {
      const options = v.options
      v.checkedList = options.map((el) => el.value)
    } else {
      v.checkedList = []
    }
  }

  // 单选
  function onCheckChange (column){
    let v = state.value[column.key]
    if(v.checkedList.length && (v.checkedList.length === v.options.length)){
      v.checkAll = true
    } else {
      v.checkAll = false
    }
  }

  // 取消全选的时候
  function handleReset(column){
    let v = state.value[column.key]
    v.checkAll = false
    v.indeterminate = false
    v.checkedList = []
    v.inputValue = ''
    v.requestValueList = []
    v.requestValue = ''
    v.searchText = ''
    handleInputChange('', column)
  }

  // 标签页清空所有的参数
  function removeAll() {
    resultList.value.forEach((item) => {
      let v = state.value[item.key]
      v.checkedList = []
      v.indeterminate = false
      v.checkAll = false
      v.inputValue = ''
      v.requestValueList = []
      v.requestValue = ''
      v.searchText = ''
      handleInputChange('', item)
    })
    resultList.value = []
    searchFun()
  }

  // 单个移除
  function remove(item){
    let v = state.value[item.key]
    v.checkedList = []
    v.indeterminate = false
    v.checkAll = false
    v.inputValue = ''
    v.requestValueList = []
    v.requestValue = ''
    v.searchText = ''
    resultList.value = resultList.value.filter((v) => v.key !== item.key)
    handleInputChange('', item)
    searchFun()
  }
   // 输入框改变时
  function handleInputChange(searchText, column){
    if(column.formType == 'select'){
      state.value[column.key].options = getColumns(column, searchText)
    }
  }

  // 点击确定
  function handleSearch(selectedKeys, confirm, column){
    getResult(column)
    confirm()
    searchFun()
  }

  return {
    initState,
    getResult,
    getColumns,
    onCheckAllChange,
    onCheckChange,
    handleInputChange,
    handleSearch,
    handleReset,
    removeAll,
    remove
  }
}